import React, { useRef, ElementRef, forwardRef, useImperativeHandle } from 'react';
import { Form, Input } from '@block/plug';
import { cloneDeep } from 'lodash';
import { CollapseList, ParkerRichText } from '@src/components';
import { getUUid } from '@src/utils';
import { APPENDIX_LIST_MAX, APPENDIX_MAX_LENGTH } from '../../constant';
import './AuditAppendix.scss';

interface Props extends DefaultToEditItem {
  value?: AuditAppendixItem[];
  onChange?: (val: AuditAppendixItem[]) => void;
  mode?: Mode;
}

interface Handle {
  /** 表单校验 */
  onValidate: () => boolean;
}

/**
 * 附录
 */

const AuditAppendix = forwardRef<Handle, Props>((props, ref) => {
  const { value, onChange, mode } = props;

  /** 头部表单Form列表 */
  const headerFormListRef = useRef<Array<Form>>([]);
  /** 内容表单Form列表 */
  const contentFormListRef = useRef<Array<Form>>([]);
  /** 富文本实例列表 */
  const richTextListRef = useRef<Array<ElementRef<typeof ParkerRichText>>>([]);

  /** 新增数据 */
  const getAddInitData = (): Partial<AuditAppendixItem> => ({
    appendixId: getUUid('string') as string,
  });

  /**
   * 列表change事件
   * @param val 新列表值
   */
  const handleListChange = (val: AuditAppendixItem[]) => {
    onChange?.(val);
  };

  /**
   * 附录表单change事件
   * @param key formItemKey
   * @param val item值
   * @param index 附录下标
   */
  const handleFormChange = (key: string, val, index: number) => {
    const newDataList = cloneDeep(value);
    newDataList[index] = { ...(newDataList?.[index] ?? {}), [key]: val };
    onChange?.(newDataList);
  };

  const handleValidate = () => {
    let validate = true;
    headerFormListRef.current?.forEach((formRef) => {
      if (formRef) {
        const headerValidate = formRef?.validateFields();
        if (validate && !headerValidate) validate = false;
      }
    });
    contentFormListRef.current?.forEach((formRef) => {
      if (formRef) {
        const contentValidate = formRef?.validateFields();
        if (validate && !contentValidate) validate = false;
      }
    });
    return validate;
  };

  useImperativeHandle(ref, () => ({ onValidate: handleValidate }));

  const renderCardHeadSelect = (val: AuditAppendixItem, index: number) => {
    const { title } = val ?? {};
    return (
      <Form
        className="audit-appendix-header-form"
        ref={(formRef: Form) => {
          headerFormListRef.current[index] = formRef;
        }}
        defaultFieldsValue={{ title }}
        mode={mode}
        onFieldValueChange={(formKey, formVal) => handleFormChange(formKey, formVal, index)}
      >
        <Form.Item
          formItemKey="title"
          label="附录标题："
          rules={[
            { required: true, whitespace: true, message: '请输入附录标题' },
            { max: 50, message: '不允许超过50字符' },
          ]}
        >
          {({ value: titleValue }) => {
            if (mode === 'edit' || titleValue?.length > 0) {
              return (
                <Input
                  toFormItem
                  dispatchChange={['onInput']}
                  placeholder="输入不超过50字符"
                  showCount
                  maxLength={50}
                />
              );
            }
            return '-';
          }}
        </Form.Item>
      </Form>
    );
  };

  const renderCardContent = (val: AuditAppendixItem, index: number) => {
    const { content } = val ?? {};
    return (
      <Form
        ref={(formRef: Form) => {
          contentFormListRef.current[index] = formRef;
        }}
        defaultFieldsValue={{ content }}
        onFieldValueChange={(formKey, formVal) => handleFormChange(formKey, formVal, index)}
      >
        <Form.Item
          formItemKey="content"
          label="附录内容："
          rules={[
            { required: true, whitespace: true, message: '请输入附录内容' },
            {
              validator: (config, textVal: string, callback: (str?: string) => void) => {
                if (richTextListRef.current?.[index]?.getTextCnt() > APPENDIX_MAX_LENGTH) {
                  callback(`建议不超过${APPENDIX_MAX_LENGTH}字符`);
                } else callback();
              },
            },
          ]}
        >
          {({ value: contentValue }) => {
            if (mode === 'edit' || contentValue?.length > 0) {
              return (
                <ParkerRichText
                  toFormItem
                  ref={(richTextRef: ElementRef<typeof ParkerRichText>) => {
                    richTextListRef.current[index] = richTextRef;
                  }}
                  mode={mode}
                  placeholder={`建议不超过${APPENDIX_MAX_LENGTH}字符`}
                  showCount
                  maxLength={APPENDIX_MAX_LENGTH}
                />
              );
            }
            return '-';
          }}
        </Form.Item>
      </Form>
    );
  };
  return (
    <CollapseList<Partial<AuditAppendixItem>>
      className="audit-appendix"
      title={(val, index) => `附录${index + 1}`}
      // @ts-expect-error
      defaultValue={mode === 'edit' ? [0] : undefined}
      multiple
      maxLength={APPENDIX_LIST_MAX}
      expandIconPosition="end"
      addInitData={getAddInitData}
      data={value}
      keyField="appendixId"
      mode={mode}
      onChange={handleListChange}
      renderHeaderSelect={renderCardHeadSelect}
      renderContent={renderCardContent}
      getContainer={() => document.querySelector('.project-detail-content') || document.body}
    />
  );
});

export default AuditAppendix;
